<template>
  <div id="cart" >
      <div class="cart-item">
          <img :src="goods.img" alt="" class="goods-img">
          <div class="goods-info">
              <a href="">{{goods.name}}</a>
              <p class="price">￥{{goods.price}}</p>
          </div>
          <div class="goods-amount">
              <counter @changeCounter="compute" :amount="goods.amount"></counter>
          </div>
          <p class="goods-total">￥{{goods.total}}</p>
      </div>
      
  </div>
</template>

<script>
import store from '../store.js'
import Counter from './Counter.vue'
export default {
    data(){
        return {
            goods:{
                name:'联想ThinkPad E580',
                img:'img/img.jpg',
                price:350,
                amount:0,
                total:0
            },
            state:store.state
        }
    },
    components:{
        Counter
    },
    props: {

    },
    methods:{
        compute(num){//出发事件后计算金额和同步全局变量
            this.goods.amount = num;
            store.setNum(num);//同步全局变量state
            this.goods.total = this.goods.price * this.goods.amount;
        }
    },
    watch:{
        'state':{//监听全局变量state,并与商品数量同步
            handler(newVal){
                this.goods.amount = newVal.num;
            },
            deep:true,
            immediate: false,
        }
    }
}
</script>


<style>
    #cart{
        width:50%;
        margin:50px auto;
        border:1px solid #dedede;
    }
    .cart-item{
        width:100%;
        height:300px;
        display: flex;
        justify-content: space-around;
        align-items: center;
    }
    .goods-img{
        width: 200px;
        height: 200px;
        flex:none
    }
    .goods-info{
        width: 200px;
        flex:auto;
    }
    .goods-amount{
        width: 200px;
        flex:auto;
    }
    .goods-total{
        width: 100px;
        flex:none;
    }
</style>